package com.zch.user.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zch.user.entity.User;
import com.zch.user.service.UserService;
import com.zch.user.service.impl.UserServiceImpl;
import com.zch.user.util.PageUtil;
import com.zch.user.util.PasswordLock;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/UserServlet")
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    UserService us = new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//System.out.println(6666);
		String method = request.getParameter("method");
		if("login".equals(method)){
			doLogin(request,response);
		}else if("add".equals(method)){
			addUser(request,response);
		}else if("delete".equals(method)){
			delete(request,response);
		}else if("update".equals(method)){
			update(request,response);
		}else if("select".equals(method)){
			getAllUsers(request,response);
		}else if("out".equals(method)){
			doOut(request,response);
		}else if("getUser".equals(method)){
			getUser(request,response);
		}else if("ajax1".equals(method)){
			checkuName(request,response);
		}else if("ajax2".equals(method)){
			checkPwd(request,response);
		}
	}

	private void checkPwd(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String pwd = request.getParameter("orgpwd");
		//加密
		String pwd2 = PasswordLock.Md5Lock1(pwd);
		PrintWriter out = response.getWriter();
		out.print(pwd2);
		
	}

	private void checkuName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uName = request.getParameter("uName");
		PrintWriter out = response.getWriter();
		if(uName==""){
			System.out.println("uName为空");
			out.print("");
			return;
		}
		
		List<User> list = us.getAllUser();
		if(list!=null){
			for(int i = 0; i < list.size(); i++){
				if(uName.equals(list.get(i).getuName())){//用户名存在
					out.print("false");
					return;
				}
				if(i == list.size()-1){
					out.println("true");
					return;
				}
			}
		}
		
	}

	private void getUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String uIdStr = request.getParameter("uId");
		int uId = Integer.parseInt(uIdStr);
		User user = us.getUser(uId);
		request.setAttribute("user", user);
		request.getRequestDispatcher("user/update.jsp").forward(request, response);;
		
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uName = request.getParameter("uName");
		String password = request.getParameter("password");
		Map<String, Object> map = us.doLogin(uName, password);
		boolean isLogin = (boolean)map.get("isLogin");
		HttpSession session = request.getSession();
		PrintWriter out = response.getWriter();
		if(isLogin){//登录成功
			User user1 = (User)map.get("user");
			session.setAttribute("user1", user1);
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('登录成功！');window.location.href='UserServlet?method=select';</script>");
		}else{//登录失败
			String msg = (String) map.get("msg");
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('"+msg+"');window.location.href='index.jsp';</script>");
		}
		
	}

	private void addUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uName = request.getParameter("uName");
		String password = request.getParameter("password");
		String rName = request.getParameter("rName");
		String tel = request.getParameter("tel");
		User user = new User(uName, PasswordLock.Md5Lock1(password), rName, tel);
		boolean flag = us.addUser(user);
		PrintWriter out = response.getWriter();
		if (flag) {// 注册成功
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('注册成功！');window.location.href='index.jsp';</script>");
		} else {// 注册失败
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('注册失败！');window.location.href='user/add.jsp';</script>");
		}
		
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uIdStr = request.getParameter("uId");
		int uId = Integer.parseInt(uIdStr);
		boolean flag = us.deleteUser(uId);
		
		PrintWriter out = response.getWriter();
		if (flag) {// 刪除成功
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('刪除成功！');window.location.href='UserServlet?method=select';</script>");
		} else {// 刪除失败
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('刪除失败！');window.location.href='UserServlet?method=select';</script>");
		}
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String uIdStr = request.getParameter("uId");
		int uId = Integer.parseInt(uIdStr);
		String uName = request.getParameter("uName");
		String password = request.getParameter("password2");
		String rName = request.getParameter("rName");
		String tel = request.getParameter("tel");
		User user = new User(uId,uName, PasswordLock.Md5Lock1(password), rName, tel);
		boolean flag = us.updateUser(user);
		PrintWriter out = response.getWriter();
		if (flag) {// 修改成功
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('修改成功！');window.location.href='UserServlet?method=select';</script>");
		} else {// 修改失败
			out.print("<head><meta charset='utf-8'></head>");
			out.print("<script language='javascript'>alert('修改失败！');window.location.href='user/update.jsp';</script>");
		}
	}

	private void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		String uName = request.getParameter("uName");
		String rName = request.getParameter("rName");
		String tel = request.getParameter("tel");
		String pageIndexStr = request.getParameter("pageIndex");
		if(pageIndexStr==null||pageIndexStr==""){
			pageIndexStr = "1";
		}
		int pageIndex = Integer.parseInt(pageIndexStr);
		System.out.println(pageIndex);
		//获得用户列表
		List<User> list = us.getAllUserByPage(uName, rName, tel, pageIndex);
		//获得总数据量
		int counts = us.getTotalCounts(uName, rName, tel);
		//获得总页码
		int totalPages = us.getTotalPages(uName, rName, tel);
		
		request.setAttribute("i", (pageIndex - 1)*PageUtil.PAGE_SIZE);
		request.setAttribute("uName", uName);
		request.setAttribute("rName", rName);
		request.setAttribute("tel", tel);
		request.setAttribute("pageIndex", pageIndex);
		request.setAttribute("list", list);
		request.setAttribute("totalCounts", counts);
		request.setAttribute("totalPages", totalPages);
		request.getRequestDispatcher("user/select.jsp").forward(request, response);;
		
	}

	private void doOut(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 获得session对象
		HttpSession session = request.getSession();
		// 失效---session中存的值
		session.invalidate();
		// 重定向回登陆页面
		response.sendRedirect("index.jsp");
	}

}
